import React, { FC, useState, useEffect } from 'react'
import QuestionCard from '../components/QuestionCard'
// import style from './List2.module.css'
import { produce } from 'immer'

const List2: FC = () => {
  useEffect(() => {
    console.log('加载 Ajax 网络请求')

    return () => {
      console.log('销毁')
    }
  }, [])

  const [questionList, setQuestionList] = useState([
    { id: 'q1', title: '问卷1', isPublished: false },
    { id: 'q2', title: '问卷2', isPublished: false },
    { id: 'q3', title: '问卷3', isPublished: false },
    { id: 'q4', title: '问卷4', isPublished: false },
  ])
  const [count, setCount] = useState(0)

  /* useEffect(() => {
    console.log('questionList changed')
  }, [questionList]) */

  /* useEffect(() => {
    console.log('count changed')
  }, [count]) */

  function add() {
    setCount(count + 1)
    // setQuestionList(questionList.concat({ id: 'q5', title: '问卷 5', isPublished: false }))
    setQuestionList(
      produce(draft => {
        draft.push({ id: 'q5', title: '问卷 5', isPublished: false })
      })
    )
  }

  function del(id: string) {
    setQuestionList(
      /* questionList.filter(question => {
        if (question.id !== id) {
          return true
        }
      }) */
      produce(draft => {
        const idx = draft.findIndex(q => q.id === id)
        draft.splice(idx, 1)
      })
    )
  }

  function pubishQuestion(id: string) {
    setQuestionList(
      /* questionList.map(q => {
        if (q.id === id) {
          q.isPublished = true
        }

        return q
      }) */
      produce(draft => {
        for (let i = 0; i < draft.length; i++) {
          const item = draft[i]
          if (item.id === id) {
            item.isPublished = true
            break
          }
        }
      })
    )
  }

  return (
    <div>
      <h1>问卷列表页 2</h1>
      <div>
        {questionList.map(question => {
          const { id, title, isPublished } = question
          return (
            <QuestionCard
              key={id}
              id={id}
              title={title}
              isPublished={isPublished}
              deleteQuestion={del}
              publishQuestion={pubishQuestion}
            />
          )
        })}
      </div>
      <div>
        <button onClick={add}>新增问卷</button>
      </div>
    </div>
  )
}

export default List2
